var MY_CLINIC_PARAM_CONF = (function() {
	function initParams(target) {
		$('div#rightPanel>div.panel').hide();
		$('div#' + target).show();
		
		if (target === 'invoice') { //发票号设置
			MY_CLINIC_PARAM_CONF.loadInvoiceInfo();
			return ;
		}
		
		WeKnow.loading();
		$.ajax({ 
			type: "POST", 
			url: "wncrm_clinic_param_conf.do/load", 
			dataType: "json",
			data: null,
			async: false,
			success: function(data) {
				if (data.errcode == 0) {
					var conf = data.conf;
					if (target === 'workflow') { // 门诊流程设置
						$('select#warehouseFlg').val(conf.warehouseFlg);
						$('select#zerostockFlg').val(conf.zerostockFlg);
						$('select#chargeAloneFlg').val(conf.chargeAloneFlg);
						$('select#dispensingAloneFlg').val(conf.dispensingAloneFlg);
//						if (conf.warehouseFlg == 1) {
//							$('select#zerostockFlg').prop('disabled', false);
//						}
						$('select#arrearsFlg').val(conf.arrearsFlg);
					} else if (target === 'dr-workspace') {
						$('select#drWorkspaceFeeFlg').val(conf.drWorkspaceFeeFlg);
						$('select#dosageAutoFlg').val(conf.dosageAutoFlg);
						$('select#daysAutoFlg').val(conf.daysAutoFlg);
						$('select#drWorkspaceFeeModifyFlg').val(conf.drWorkspaceFeeModifyFlg);
						$('select#drWorkspaceWestTogetherFlg').val(conf.drWorkspaceWestTogetherFlg);
					} else if (target === 'member-rule') {//病历号规则设置
						var a = data.memberRule;
						$('#prefix').val( a.prefix == null?'':a.prefix );
						if ( a.dateTp ){
							 $('input:radio[name=dateTp]').filter('[value="' + a.dateTp +  '"]').prop("checked", true); // radio on
						} else{
							$('input:radio[name=dateTp]').eq('0').prop("checked", true); // radio on
						}
						$('#serialNumberLen').val(a.serialNumberLen);
						
						var prvNo = editPreNo();// 预览病历号
						$('label#noPreview').text(prvNo);
					} else if (target === 'prescription') {
						$('input#westPatentTogetherTag').val(conf.drWorkspaceWestTogetherFlg);
						loadPrescriptionSettings();
					}
				} else {
					WeKnow.systemMsg("系统异常");
				}
			},
			error: function() {
				WeKnow.systemMsg("系统异常");
			}
		});
		WeKnow.closeLoading();
	}

	function loadPrescriptionSettings() {
		var $tbody = $('#prescriptionTBody');
		$tbody.empty();
		$('#prescriptionSettingID').val('');
		var togetherFlg = $('input#westPatentTogetherTag').val();

		var postUrl = "wncrm_outpatient.do/menu/load";

		$.post(postUrl, {}, function (data, status) {
			if (data.errcode === 0) {
				var tableHTML = '';
				if (data.menuModel) {
					$('#prescriptionSettingID').val(data.menuModel.id);
					tableHTML = '<tr>' +
						'<td>病历</td>' +
						'<td><input name="medicalRecord" type="checkbox" ' + (data.menuModel.medicalRecord > 0 ? 'checked="true"' : 'false') + '"></td>' +
						'</tr>' +
						'<tr>' +
						'<td>口腔病历</td>' +
						'<td><input name="mouthMedicalRecord" type="checkbox" ' + (data.menuModel.mouthMedicalRecord > 0 ? 'checked="true"' : '') + '"></td>' +
						'</tr>' +
						'<tr>' +
						'<td>中医病历</td>' +
						'<td><input name="chineseMedicalRecord" type="checkbox" ' + (data.menuModel.chineseMedicalRecord > 0 ? 'checked="true"' : '') + '"></td>' +
						'</tr>' +
						'<tr>';
					if (togetherFlg) {
						tableHTML += '<td>西药/中成药</td>' +
							'<td><input name="westPrescription" type="checkbox" ' + (data.menuModel.westPrescription > 0 ? 'checked="true"' : '') + '"></td>' +
							'</tr>' +
							'<tr>' +
							'<td>中药</td>' +
							'<td><input name="chinesePrescription" type="checkbox" ' + (data.menuModel.chinesePrescription > 0 ? 'checked="true"' : '') + '"></td>' +
							'</tr>';
					} else {
						tableHTML += '<td>西药</td>' +
							'<td><input name="westPrescription" type="checkbox" ' + (data.menuModel.westPrescription > 0 ? 'checked="true"' : '') + '"></td>' +
							'</tr>' +
							'<tr>' +
							'<td>中药</td>' +
							'<td><input name="chinesePrescription" type="checkbox" ' + (data.menuModel.chinesePrescription > 0 ? 'checked="true"' : '') + '"></td>' +
							'</tr>' +
							'<tr>' +
							'<td>中成药</td>' +
							'<td><input name="chinesePatentPrescription" type="checkbox" ' + (data.menuModel.chinesePatentPrescription > 0 ? 'checked="true"' : '') + '"></td>' +
							'</tr>';
					}
					tableHTML +=
						'<tr><td>处置项目</td>' +
						'<td><input name="disposalPrescription" type="checkbox" ' + (data.menuModel.disposalPrescription > 0 ? 'checked="true"' : '') + '"></td>' +
						'</tr>' +
						'<tr><td>治疗项目</td>' +
						'<td><input name="treatment" type="checkbox" ' + (data.menuModel.treatment > 0 ? 'checked="true"' : '') + '"></td>' +
						'</tr>' +
						'<tr>' +
						'<td>检验检查</td>' +
						'<td><input name="test" type="checkbox" ' + (data.menuModel.test > 0 ? 'checked="true"' : '') + '"></td>' +
						'</tr>' +
						'<tr>' +
						'<td>健康管理</td>' +
						'<td><input name="healthManagement" type="checkbox" ' + (data.menuModel.healthManagement > 0 ? 'checked="true"' : '') + '"></td>' +
						'</tr>';
				} else {
					tableHTML = '<tr>' +
						'<td>病历</td>' +
						'<td><input name="medicalRecord" type="checkbox" checked="true"></td>' +
						'</tr>' +
						'<tr>' +
						'<td>口腔病历</td>' +
						'<td><input name="mouthMedicalRecord" type="checkbox" checked="true"></td>' +
						'</tr>' +
						'<tr>'+
						'<td>中医病历</td>' +
						'<td><input name="chineseMedicalRecord" type="checkbox" ' + (data.menuModel.chineseMedicalRecord > 0 ? 'checked="true"' : '') + '"></td>' +
						'</tr>' +
						'<tr>';
					if (togetherFlg) {
						tableHTML +=
							'<td>西药/中成药</td>' +
							'<td><input name="westPrescription" type="checkbox" checked="true"></td>' +
							'</tr>' +
							'<tr>' +
							'<td>中药</td>' +
							'<td><input name="chinesePrescription" type="checkbox" checked="true"></td>' +
							'</tr>';
					} else {
						tableHTML += '<td>西药</td>' +
							'<td><input name="westPrescription" type="checkbox" checked="true"></td>' +
							'</tr>' +
							'<tr>' +
							'<td>中药</td>' +
							'<td><input name="chinesePrescription" type="checkbox" checked="true"></td>' +
							'</tr>' +
							'<tr>'+
							'<td>中成药</td>' +
							'<td><input name="chinesePatentPrescription" type="checkbox" checked="true"></td>' +
							'</tr>';
					}
					tableHTML +=
						'<tr><td>处置项目</td>' +
						'<td><input name="disposalPrescription" type="checkbox" checked="true"></td>' +
						'</tr>' +
						'<tr><td>治疗项目</td>' +
						'<td><input name="treatment" type="checkbox" checked="true"></td>' +
						'</tr>' +
						'<tr>' +
						'<td>检验检查</td>' +
						'<td><input name="test" type="checkbox" checked="true"></td>' +
						'</tr>' +
						'<tr>' +
						'<td>健康管理</td>' +
						'<td><input name="healthManagement" type="checkbox" checked="true"></td>' +
						'</tr>';
					
				}
				$tbody.append(tableHTML);
			} else if (data.errcode === -1) {
				if (data.errorMsg) {
					WeKnow.errorMsg(data.errorMsg);
				} else {
					WeKnow.errorMsg("系统出错，请稍后再试！");
				}
			}
		});
	}
	
	function savePrescription() {
			// 西医、中医、口腔 病历至少选1个
			if (!$('input[name="medicalRecord"]').prop('checked') &&
				!$('input[name="mouthMedicalRecord"]').prop('checked' &&
				!$('input[name="chineseMedicalRecord"]').prop('checked'))
				&& !$('input[name="chinesePrescription"]').prop('checked')
				&& !$('input[name="treatment"]').prop('checked')
				&& !$('input[name="test"]').prop('checked')
				&& !$('input[name="healthManagement"]').prop('checked')
				&& !$('input[name="disposalPrescription"]').prop('checked')) {
				
				if (!$('input[name="westPrescription"]').prop('checked') && $('input#westPatentTogetherTag').val() * 1) {
					WeKnow.errorMsg("至少显示一项");
					return;
				} else if (!$('input[name="westPrescription"]').prop('checked') && !$('input[name="chinesePatentPrescription"]').prop('checked') && !($('input#westPatentTogetherTag').val() * 1)) {
					WeKnow.errorMsg("至少显示一项");
					return;
				}
			}

			var postUrl = "wncrm_outpatient.do/menu/save";

			var params = {
				medicalRecord: $('input[name="medicalRecord"]').prop('checked') ? 1 : -1,
				mouthMedicalRecord: $('input[name="mouthMedicalRecord"]').prop('checked') ? 1 : -1,
				disposalPrescription: $('input[name="disposalPrescription"]').prop('checked') ? 1 : -1,
				chineseMedicalRecord: $('input[name="chineseMedicalRecord"]').prop('checked') ? 1 : -1,
				westPrescription: $('input[name="westPrescription"]').prop('checked') ? 1 : -1,
				chinesePrescription: $('input[name="chinesePrescription"]').prop('checked') ? 1 : -1,
				treatment: $('input[name="treatment"]').prop('checked') ? 1 : -1,
				test: $('input[name="test"]').prop('checked') ? 1 : -1,
				healthManagement: $('input[name="healthManagement"]').prop('checked') ? 1 : -1
			};
			if ($('input#westPatentTogetherTag').val() * 1) {
				params.chinesePatentPrescription = params.westPrescription;
			} else {
				params.chinesePatentPrescription = $('input[name="chinesePatentPrescription"]').prop('checked') ? 1 : -1;
			}
			var id = $('#prescriptionSettingID').val();
			if (id) {
				params.id = 1 * id;
			}

			WeKnow.loading();

			$.ajax({
				type: 'POST',
				url: postUrl,
				data: JSON.stringify(params),
				dataType: 'json',
				contentType: 'application/json',
				success: function (data) {
					WeKnow.closeLoading();
					if (data.errcode === 0) {
						WeKnow.successMsg("保存成功");
					} else if (data.errcode === -1) {
						if (data.errorMsg) {
							WeKnow.errorMsg(data.errorMsg);
						} else {
							WeKnow.errorMsg("系统出错，请稍后再试！");
						}
					}
				},
				error: function (err, data) {
					WeKnow.closeLoading();
				}
			});

	}
	
	/* 生成设置预览 */
	function editPreNo(){
		
		var prvNo = '';
		
		prvNo+=$('#prefix').val();
		// 日期规则
		var datetime = new Date();
	    var year = datetime.getFullYear();
	    var month = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
	    var date = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();
		var dateTp = $('input:radio[name=dateTp]:checked').val();  //获取被选中Radio的Value值
		switch ( dateTp )	{
			case '1'://年
				prvNo += year.toString();
				break;
			case '2'://年月
				prvNo += (year.toString()+month.toString()) ;
				break;
			case '3'://年月日
				prvNo += (year.toString()+month.toString()+date.toString()) ;
				break;
			default:
				break;
		}
		// 长度
		var serialNumberLen = Number( $('#serialNumberLen').val() );
		// 起始号码[跟长度补0处理]
		prvNo+= (Array(serialNumberLen).join(0) + 1).slice(-serialNumberLen);  
		
		return prvNo;
	}
	
	/**
	 * 保存 病历号规则设置
	 */
	function saveMemberRule() {
		
		var a={};
		prefix = $.trim( $('#prefix').val());//前缀
		if ( prefix != '' ){
			a.prefix = prefix;
		}
		a.dateTp = $('input:radio[name=dateTp]:checked').val();  //获取被选中Radio的Value值
		a.serialNumberLen = $('#serialNumberLen').val();
		
		WeKnow.loading();
		$.ajax({ 
			type: "POST", 
			url: "wncrm_clinic_member_rule.do/save",
			dataType: "json",
			contentType: "application/json;charset=utf-8",
			data: JSON.stringify(a),
			async: false,
			success: function(data) {
				
				WeKnow.closeLoading();
				
				if (!WeKnow.filterAjaxResult(data)) return false; // session过期check
				
				if (data.errcode == 0) {
					WeKnow.successMsg("保存成功");
				}
			},
			error: function() {
				WeKnow.systemMsg("系统异常");
			}
		});
	}
	
	/**
	 * 保存发票信息
	 */
	function saveInvoiceInfo() {
		
		var $invoiceCode = $('#invoiceCode');
		if (! $.trim( $invoiceCode.val()).length ){
			WeKnow.errorMsg("请输入发票代码");
			$invoiceCode.focus();
			return;
		}
		var invoiceCode = $invoiceCode.val();
		
		if ( !MY_VALIDATOR.isNumber(invoiceCode) ){
			WeKnow.errorMsg("请输入正整数");
			$invoiceCode.focus();
			return;
		}
		
		var $invoiceNo = $('#invoiceNo');
		if (! $.trim( $invoiceNo.val()).length ){
			WeKnow.errorMsg("请输入发票号码");
			$invoiceNo.focus();
			return;
		}
		invoiceNo = $invoiceNo.val();
		
		if ( !MY_VALIDATOR.isNumber(invoiceNo) ){
			WeKnow.errorMsg("请输入正整数");
			$invoiceNo.focus();
			return;
		}
		var invoiceNo = $.trim( $invoiceNo.val());

		var $invoiceStartNo = $('#invoiceStartNo');
		var invoiceStartNo = $.trim( $invoiceStartNo.val());
		if (! invoiceStartNo.length ){
			WeKnow.errorMsg("请输入发票号码");
			$invoiceStartNo.focus();
			return;
		}

		if ( !MY_VALIDATOR.isNumber(invoiceStartNo) ){
			WeKnow.errorMsg("请输入正整数");
			$invoiceStartNo.focus();
			return;
		}
		invoiceStartNo = invoiceStartNo * 1;

		var $invoiceEndNo = $('#invoiceEndNo');
		var invoiceEndNo = $.trim( $invoiceEndNo.val());
		if (! invoiceEndNo.length ){
			WeKnow.errorMsg("请输入发票号码");
			$invoiceEndNo.focus();
			return;
		}

		if ( !MY_VALIDATOR.isNumber(invoiceEndNo) ){
			WeKnow.errorMsg("请输入正整数");
			$invoiceEndNo.focus();
			return;
		}
		invoiceEndNo = invoiceEndNo * 1;

		if(! (invoiceStartNo < invoiceEndNo)) {
			WeKnow.errorMsg("截止号码必须大于起始号码。");
			$invoiceStartNo.focus();
			return;
		}

		if(! (invoiceStartNo <= invoiceNo && invoiceNo <= invoiceEndNo)) {
			WeKnow.errorMsg("当前使用号码必须在起止号码区间内。");
			$invoiceNo.focus();
			return;
		}
		
		WeKnow.loading();
		$.ajax({ 
			type: "POST", 
			url: "wncrm_clinic_Invoice.do/save",
			dataType: "json",
			data: {invoiceCode:invoiceCode,invoiceNo:invoiceNo,invoiceStartNo:invoiceStartNo,invoiceEndNo:invoiceEndNo},
			async: false,
			success: function(data) {
				
				WeKnow.closeLoading();
				
				if (!WeKnow.filterAjaxResult(data)) return false; // session过期check
				
				if (data.errcode == 0) {
					WeKnow.successMsg("更新成功");
				}
			},
			error: function() {
				WeKnow.systemMsg("系统异常");
			}
		});
	}
	
	/**
	 * load发票信息
	 */
	function loadInvoiceInfo() {
		
		WeKnow.loading();
		
		// 清空输入框
		$('div#invoice').find('input').val('');
		
		$.ajax({ 
			type: "POST", 
			url: "wncrm_clinic_Invoice.do/load",
			dataType: "json",
			data: {},
			async: false,
			success: function(data) {
				if (!WeKnow.filterAjaxResult(data)) return false; // session过期check
				
				if (data.errcode == 0 && 'invoiceInfo' in data) {
					$('#invoiceCode').val(data.invoiceInfo.invoiceCode);
					$('#invoiceNo').val(data.invoiceInfo.invoiceNo);
					$('#invoiceStartNo').val(data.invoiceInfo.invoiceStartNo);
					$('#invoiceEndNo').val(data.invoiceInfo.invoiceEndNo);
				}
			},
			error: function() {
				WeKnow.systemMsg("系统异常");
			}
		});
		WeKnow.closeLoading();
	}
	
	return {
		initParams: initParams,
		editPreNo:editPreNo,
		saveMemberRule:saveMemberRule,
		saveInvoiceInfo:saveInvoiceInfo,
		loadInvoiceInfo:loadInvoiceInfo,
		loadPrescriptionSettings:loadPrescriptionSettings,
		savePrescription: savePrescription
	}
})();

$(document).ready(function() {
	
	// 工作区域 高度调整
	(function() {
		var panelHeight = $(window).height() - 80;
		$("div.all-screen").css({"max-height": (panelHeight) + "px", "min-height": (panelHeight) + "px", "overflow-y": "auto"});
	})();
	
	// 选择左边设置G
	$('ul#paramsGroup>li.list-group-item').on('click', function() {
		var $that = $(this);
		$that.addClass('active').siblings().removeClass('active');
		MY_CLINIC_PARAM_CONF.initParams($that.data('href'));
	});
	
	
	// 保存信息
	$('button[name="paramConfSave"]').on('click', function() {
		
		var target = $('ul#paramsGroup>li.list-group-item.active').data('href');
		if (target && target.length) {
			var params = {}; //参数
			
			if (target === 'workflow') { // 门诊流程设置
				params.warehouseFlg = $('select#warehouseFlg').val();
				params.zerostockFlg = $('select#zerostockFlg').val();
				params.chargeAloneFlg = $('select#chargeAloneFlg').val();
				params.dispensingAloneFlg = $('select#dispensingAloneFlg').val();
				params.arrearsFlg = $('select#arrearsFlg').val();
			} else if (target === 'dr-workspace') { // 医生工作站设置
				params.drWorkspaceFeeFlg = $('select#drWorkspaceFeeFlg').val();
				params.dosageAutoFlg = $('select#dosageAutoFlg').val();
				params.daysAutoFlg = $('select#daysAutoFlg').val();
				params.drWorkspaceFeeModifyFlg = $('select#drWorkspaceFeeModifyFlg').val();
				params.drWorkspaceWestTogetherFlg = $('select#drWorkspaceWestTogetherFlg').val();
			}else if (target === 'member-rule') { // 病历号规则设置
				MY_CLINIC_PARAM_CONF.saveMemberRule();
				return;
			}else if (target === 'invoice') { // 发票号设置
				MY_CLINIC_PARAM_CONF.saveInvoiceInfo();
				return;
			}

			WeKnow.loading();
			$.ajax({ 
				type: "POST", 
				url: "wncrm_clinic_param_conf.do/save", 
				dataType: "json",
				data: params,
				async: false,
				success: function(data) {
					if (!WeKnow.filterAjaxResult(data)) return false; // session过期check
					if (data.errcode == 0) {
						WeKnow.successMsg('保存成功');
					} else {
						WeKnow.systemMsg("系统异常");
					}
					
				},
				error: function() {
					WeKnow.systemMsg("系统异常");
				}
			});
			WeKnow.closeLoading();
		} else {
			WeKnow.systemMsg("系统异常");
		}
	});
	
	// 取消
	$('button[name="paramConfCancel"]').on('click', function() {
		$('ul#paramsGroup>li.list-group-item.active').click();
	});
	
	// 显示 门诊流程设置
	$('ul#paramsGroup>li.list-group-item:first').click();
	
	// 病历号预览联动
	$('input:radio,select').on('change',function(){
		// 预览
		var prvNo = MY_CLINIC_PARAM_CONF.editPreNo();
		$('label#noPreview').text(prvNo);
	});
	$('input#prefix').on('input',function(){
		// 预览
		var prvNo = MY_CLINIC_PARAM_CONF.editPreNo();
		$('label#noPreview').text(prvNo);
	});
	$('button[name="prescriptionConfSave"]').on('click', function () {
		MY_CLINIC_PARAM_CONF.savePrescription();
	})
	$('button[name="prescriptionConfCancel"]').on('click', function () {
		MY_CLINIC_PARAM_CONF.loadPrescriptionSettings();
	})
});